﻿using System;
using System.Linq;
using System.IO;

namespace WindowsTest
{
    /// <summary>
    /// 文件夹清空类
    /// </summary>
    class FilesClean
    {
        /// <summary>
        /// 清空文件夹
        /// </summary>
        /// <param name="path">要清空文件夹的路径</param>
        /// <param name="isDelCurrentFolder">是否删除当前文件夹 </param>
        public static void Clean(string path, bool isDelCurrentFolder = false)
        {
            if (isDelCurrentFolder)
            {
                cleanUp(path);
            }
            else if (Directory.Exists(path))
            {
                var ds = Directory.GetDirectories(path);
                if (ds.Any())
                {
                    for (int i = 0; i < ds.Count(); i++)
                    {
                        cleanUp(ds[i]);
                    }
                }

                //删除该路径下面的所有文件
                var fs = Directory.GetFiles(path);
                if (fs.Any())
                {
                    for (int i = 0; i < fs.Count(); i++)
                    {
                        File.Delete(fs[i]);
                    }
                }
            }
        }

        /// <summary>
        /// 删除文件夹下的所有文件夹及文件，并删该文件夹
        /// </summary>
        /// <param name="path">要删除文件夹路径</param>
        private static void cleanUp(string path)
        {
            try
            {
                if (Directory.Exists(path))
                {
                    var ds = Directory.GetDirectories(path);
                    if (ds.Any())
                    {
                        for (int i = 0; i < ds.Count(); i++)
                        {
                            cleanUp(ds[i]);
                        }
                    }

                    //删除所有文件
                    var fs = Directory.GetFiles(path);
                    if (fs.Any())
                    {
                        for (int i = 0; i < fs.Count(); i++)
                        {
                            File.Delete(fs[i]);
                        }
                    }

                    //删除当前文件夹
                    Directory.Delete(path);
                }
            }
            catch (Exception e)
            {
                LogService.Error(e);
            }
        }
    }
}
